package com.enqualcomm.kids.activities;

import android.graphics.Rect;
import android.net.Uri;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.enqualcomm.kids.R;
import com.enqualcomm.kids.base.BaseActivity;
import com.enqualcomm.kids.bean.StringMessage;
import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.enqualcomm.kids.config.userdefault.UserTerminalDefault;
import com.enqualcomm.kids.mvp.NetworkModel;
import com.enqualcomm.kids.mvp.oscard.PicturesAdapter;
import com.enqualcomm.kids.mvp.pay.PayPopupWindow;
import com.enqualcomm.kids.mvp.pay.PayUtil;
import com.enqualcomm.kids.network.NetworkListener;
import com.enqualcomm.kids.network.SocketRequest;
import com.enqualcomm.kids.network.socket.request.OscardPictureDownParams;
import com.enqualcomm.kids.network.socket.request.OscardPicturesParams;
import com.enqualcomm.kids.network.socket.request.OscardProductsParams;
import com.enqualcomm.kids.network.socket.response.BasicResult;
import com.enqualcomm.kids.network.socket.response.OscardPicturesResult;
import com.enqualcomm.kids.network.socket.response.OscardProductsResult;
import com.enqualcomm.kids.network.socket.response.QueryUserTerminalInfoResult;
import com.enqualcomm.kids.network.socket.response.TerminallistResult;
import com.facebook.drawee.view.SimpleDraweeView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

import common.utils.DensityUtil;
import common.utils.PromptUtil;
import de.greenrobot.event.EventBus;
import rx.functions.Action1;

@EActivity(R.layout.activity_oscard_show)
public class OscardShowActivity extends BaseActivity {

    @Extra("terminal")
    TerminallistResult.Terminal terminal;
    @Extra("product")
    OscardProductsResult.Product product;

    @ViewById(R.id.cover_simpleDraweeView)
    SimpleDraweeView cover_simpleDraweeView;
    @ViewById(R.id.name_tv)
    TextView name_tv;
    @ViewById(R.id.state_tv)
    TextView state_tv;
    @ViewById(R.id.download_count_tv)
    TextView download_count_tv;
    @ViewById(R.id.size_tv)
    TextView size_tv;
    @ViewById(R.id.recyclerview)
    RecyclerView recyclerview;
    @ViewById(R.id.download_btn)
    Button download_btn;

    AppDefault appDefault;
    NetworkModel networkModel;
    int itemOffset;
    boolean needPay;
    PicturesAdapter adapter;
    private String wxOrderId;
    private PayPopupWindow popupWindow;

    @AfterViews
    void afterViews(){
        itemOffset = DensityUtil.dip2px(this, 8);
        appDefault = new AppDefault();
        networkModel = new NetworkModel();
        QueryUserTerminalInfoResult.Data info = new UserTerminalDefault(terminal.userterminalid).getInfo();
        setupTitleIcon(info, terminal.terminalid, terminal.userterminalid,"AR卡片");

        initView();
        initData();
        EventBus.getDefault().register(this);
    }

    private void initView() {
        cover_simpleDraweeView.setImageURI(Uri.parse(product.producturl));
        if ("1".equals(product.iffree)){//免费商品
            state_tv.setText("免费");
            download_btn.setText("下载AR卡片到手表");
            download_btn.setBackgroundResource(R.drawable.oscard_download_btn);
        }else if ("1".equals(product.ifbuy)){//已购商品
            state_tv.setText("已购");
            download_btn.setText("下载AR卡片到手表");
            download_btn.setBackgroundResource(R.drawable.oscard_download_btn);
        }else {//其他，显示商品单价
            state_tv.setText(product.money+"￥");
            download_btn.setText(String.format("快速支付（￥%.2f），快乐学习",Float.parseFloat(product.money)));
            download_btn.setBackgroundResource(R.drawable.oscard_pay_btn);
            needPay = true;
        }
        name_tv.setText(product.productname);
        download_count_tv.setText(product.productdownnum+"次下载");
        size_tv.setText("共"+product.productsize+"K");

        recyclerview.setHasFixedSize(true);
        recyclerview.setLayoutManager(new GridLayoutManager(this,4));
        recyclerview.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) {
                int i = itemPosition % 4;
                if (i==0) {//左边
                    outRect.set(0,itemOffset,itemOffset,0);
                }else if (i==3){//右边
                    outRect.set(itemOffset,itemOffset,0,0);
                }else {//中间
                    outRect.set(itemOffset,itemOffset,itemOffset,0);
                }
            }
        });
        adapter = new PicturesAdapter(getLayoutInflater());
        recyclerview.setAdapter(adapter);
    }

    private void initData() {
        OscardPicturesParams params = new OscardPicturesParams(appDefault.getUserkey(), appDefault.getUserid(), terminal.terminalid, product.productpayid);
        networkModel.loadDataFromServer(new SocketRequest<OscardPicturesResult>(params, new NetworkListener<OscardPicturesResult>() {
            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(OscardPicturesResult response) {
                if (response.code==0) {
                    if (response.result!=null&&!response.result.isEmpty()) {
                        fillData(response.result);
                    }
                }
            }
        }));
    }

    private void fillData(List<OscardPicturesResult.Pic> result) {
        ArrayList<Uri> uris = new ArrayList<>();
        for (OscardPicturesResult.Pic pic : result) {
            uris.add(Uri.parse(pic.picurl));
        }
        adapter.setData(uris);
    }

    @Click(R.id.download_btn)
    void download(){
        if (needPay) {
            //弹出对话框选择付款方式
            if (popupWindow==null) {
                popupWindow = PayPopupWindow.create(this);
                popupWindow.setListener(new PayPopupWindow.Listener() {
                    @Override
                    public void onAlipay() {
                        alipay();
                    }

                    @Override
                    public void onWxpay() {
                        wxpay();
                    }
                });
                popupWindow.setPrice(String.format("￥%s元",product.money));
            }
            popupWindow.show(this);
        }else {
            download_btn.setEnabled(false);
            OscardPictureDownParams params = new OscardPictureDownParams(appDefault.getUserkey(), appDefault.getUserid(), terminal.terminalid, product.productpayid,product.orderid);
                networkModel.loadDataFromServer(new SocketRequest<BasicResult>(params, new NetworkListener<BasicResult>() {
                @Override
                public void onError(VolleyError error) {
                    download_btn.setEnabled(true);
                }

                @Override
                public void onSuccess(BasicResult response) {
                    download_btn.setEnabled(true);
                    if (response.code==0){
                        PromptUtil.longToast(getApplicationContext(),"手表下载AR卡片进行中，请注意查看...");
                    }
                }
            }));
        }
    }


    private void refresh(String orderid) {
        state_tv.setText("已购");
        download_btn.setText("下载到手表");
        download_btn.setBackgroundResource(R.drawable.bg_oscard_download);
        needPay = false;
        product.orderid = orderid;
        product.ifbuy = "1";
        EventBus.getDefault().post(product);//通知上层界面刷新
    }

    @Click(R.id.title_bar_left_iv)
    void finishActivity() {
        finish();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        networkModel.onStop();
        super.onDestroy();
    }

    private void alipay(){
        download_btn.setEnabled(false);
        PayUtil.alipay(this,appDefault.getUserkey(),appDefault.getUserid(),terminal.terminalid,product.productpayid)
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String orderid) {
                        download_btn.setEnabled(true);
                        if (orderid!=null){
                            refresh(orderid);
                        }
                    }
                });
    }

    private void wxpay(){
        download_btn.setEnabled(false);
        PayUtil.wxpay(this,appDefault.getUserkey(),appDefault.getUserid(),terminal.terminalid,product.productpayid)
        .subscribe(new Action1<String>() {
            @Override
            public void call(String orderid) {
                if (orderid!=null){
                    //已发起支付，等待WXPayEntryActivity通知
                    wxOrderId = orderid;
                }else {
                    download_btn.setEnabled(true);
                }
            }
        });
    }

    public void onEvent(StringMessage stringMessage){
        if (wxOrderId!=null){
            if (StringMessage.PAY_ERROR.equals(stringMessage.msg)){
                download_btn.setEnabled(true);
                wxOrderId = null;
            }else if (StringMessage.PAY_SUCCESS.equals(stringMessage.msg)){
                refresh(wxOrderId);
                download_btn.setEnabled(true);
                wxOrderId = null;
            }
        }
    }

    @Override
    protected void onRestart() {
        if (wxOrderId!=null){//微信有时候会漏掉通知
            checkPayState();
        }

        super.onRestart();
    }

    private void checkPayState(){
        OscardProductsParams params = new OscardProductsParams(appDefault.getUserkey(), appDefault.getUserid(), terminal.terminalid);
        networkModel.loadDataFromServer(new SocketRequest<OscardProductsResult>(params, new NetworkListener<OscardProductsResult>() {
            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(OscardProductsResult response) {
                if (response.code==0){
                    List<OscardProductsResult.Data> list = response.result;
                    if (list!=null&&!list.isEmpty()){
                        for (OscardProductsResult.Data data : list) {
                            for (OscardProductsResult.Product p : data.productpay) {
                                if (product.productpayid.equals(p.productpayid)&& "1".equals(p.ifbuy)) {
                                    refresh(wxOrderId);
                                }
                            }
                        }
                    }
                }
            }
        }));
    }
}
